(function() {
    'use strict';

    /**
     * <printpdf pid="invoice.invoice_id" print-type="invoice" pdfchecked="save"></printpdf>
     *pid参数 打印内容的id
     *print-type 查询模板类型
     *pdfchecked pdf使用参数 有save保存pdf print打印pdf 和open或无参的打开pdf
     * 打印Print指令用来打印模板
     *
     */
    angular.module('webApp')
        .run(["$templateCache", "dataService",
            function($templateCache, dataService) {
                var tplName = "views/directives.printpdf.html";
                dataService.tpl(tplName).then(function(html) {
                    $templateCache.put(tplName, html);
                });
            }
        ])

    .directive('printpdf', function() {
        'use strict';
        return {
            restrict: 'E',
            template: "<a href='javascript:void(0);' class='sui-btn btn-small btn-primary' ng-click='chosePrint();'><i class='sui-icon icon-tb-shop'></i>{{checkedPdf|translate}}</a>",
            scope: {
                printType: '@',
                pid: '=',
                pdfchecked: '@'
            },
            controller: ['$scope', '$location', 'dataService', '$templateCache', '$compile', '$timeout', 'helper', '$q', 'moment', '$filter',
                function($scope, $location, dataService, $templateCache, $compile, $timeout, helper, $q, moment, $filter) {
                    $scope.title = '';
                    if ($scope.pdfchecked == 'save') {
                        $scope.checkedPdf = 'save_as_pdf';
                    } else if ($scope.pdfchecked == 'print') {
                        $scope.checkedPdf = 'Print';
                    } else {
                        $scope.checkedPdf = 'open_as_pdf';
                    }

                    $scope.chosePrint = function() {
                        console.log("dddddddddddd==",$scope.pid);
                        if ($scope.pid.length == 0) {
                            helper.myAlert('No data found');
                            return false;
                        }

                        $scope.printTemplateList($scope.printType).then(function() {
                            if ($scope.shopconfigs.length == 1 && $scope.printTplId) {
                                $scope.clickPdf();
                            } else {
                                showPop();
                            }
                        });

                        switch ($scope.printType) {
                            case "express":
                                $scope.title = "Express";
                                break;
                            case "invoice":
                                $scope.title = "Invoice";
                                break;
                            case "picking":
                                $scope.title = "Picking";
                                break;
                            case "shipping":
                                $scope.title = "Shipping";
                                break;
                            case "finance":
                                $scope.title = "Finance";
                                break;
                            case "payment":
                                $scope.title = "payment";
                                break;
                            case "trade":
                                $scope.title = "trade";
                                break;
                            case "returnform":
                                $scope.title = "Customer service";
                                break;
                        }
                    }

                    $scope.clickPdf = function() {
                        switch ($scope.printType) {
                            case "express":
                                $scope.getPdfdata();
                                break;

                            case "invoice":
                                $scope.getPdfdata();
                                break;

                            case "picking":
                                $scope.getPdfdata();
                                break;

                            case "shipping":
                                $scope.getPdfdata();
                                break;
                            case "finance":
                                $scope.getPdfdata();
                                break;
                            case "payment":
                                $scope.getPdfdata();
                                break;
                            case "trade":
                                $scope.getPdfdata();
                                break;
                            case "returnform":
                                $scope.getPdfdata();
                                break;
                        }

                        $scope.hidePopWin();
                    }

                    $scope.createPdfs = function() {
                        $timeout(function() {

                            var paperA = JSON.parse($scope.printTplId.value);
                            var notnull = true;
                            var width = 0,
                                height = 0,
                                pwidth = 0,
                                pheight = 0;
                            width = paperA.width * 3 / 4;
                            height = paperA.height * 3 / 4;
                            pdfMake.fonts = {
                                SIMFANG: {
                                    normal: 'SIMFANG.TTF',
                                    bold: 'SIMFANG.TTF',
                                    italics: 'SIMFANG.TTF',
                                    bolditalics: 'SIMFANG.TTF'
                                },
                            };

                            var docDefinition = {

                                // a string or { width: number, height: number } 单位也是pt
                                pageSize: {
                                    width: helper.px2pt(paperA.width),
                                    height: helper.px2pt(paperA.height)
                                },
                                // {
                                //     height: height + 700,
                                //     width: width + 700
                                // },

                                // 纸张方向 by default we use portrait（直版）, you can change it to landscape（横版） if you wish
                                pageOrientation: 'portrait',

                                // 边距,单位是pt [left, top, right, bottom] or [horizontal, vertical] or just a number for equal margins
                                pageMargins: [0, 0, 0, 0],

                                content: [
                                    // { text: "abc汉语能显示了吗？" }
                                ],
                                defaultStyle: {
                                    font: 'SIMFANG'
                                },
                            };

                            var imgsarray = [];
                            console.log("$scope.printPdf==========",$scope.printPdf);
                            _.map($scope.printPdf, function(v, k) {
                                _.map(v.item, function(template, key) {
                                    console.log("templatetemplatetemplate",template);
                                    if (template.type == 'text' || template.type == undefined) {
                                        var id = template.id.split('-');
                                        //                                         console.log("id", id);
                                        if (id.length <= 2) {
                                            var text = null;
                                            if (template.time == 'time') {
                                                text = moment(template.value).format("YYYY-MM-DD HH:mm:ss");
                                            } else {
                                                if (id[0] == "outstock") {
                                                    console.log("*")
                                                    text = 0;
                                                    async.map(template.values[id[0]], function(cc, callback) {
                                                        _.map(cc, function(v) {
                                                            text += v.input_price * v.num;
                                                            callback(null, null);
                                                        });
                                                    }, function(err, re) {
                                                        text = text.toFixed(2);
                                                    })
                                                } else {
                                                    text = template.value;
                                                }
                                            }
                                            console.log("texttext=",text);
                                            docDefinition.content.push({
                                                text: text + "",
                                                absolutePosition: {
                                                    x: helper.px2pt(template.x),
                                                    y: helper.px2pt(template.y)
                                                },
                                                fontSize: template.font
                                            });
                                        } else {
                                            tabledataChild(template, function(rows) {
                                                docDefinition.content.push({
                                                    table: {
                                                        // headers are automatically repeated if the table spans over multiple pages
                                                        // you can declare how many rows should be treated as headers
                                                        body: rows,
                                                         
                                                    },
                                                    absolutePosition: {
                                                        x: helper.px2pt(template.x),
                                                        y: helper.px2pt(template.y)
                                                    },
                                                    layout: 'noBorders', //表框状态  没有边框
                                                    fontSize: template.font
                                                });
                                            });

                                        }

                                    } else if (template.type == 'image') {
                                        // var img = $('img[name=' + template.id + ']').get(0);
                                        imgsarray.push(template);

                                    } else if (template.type == 'stockoutStatus') {
                                        docDefinition.content.push({
                                            text: '<out-status ng-model="' + template.value + '" stype="1"></out-status>',
                                            absolutePosition: {
                                                x: template.x,
                                                y: template.y
                                            }
                                        });
                                    } else if (template.type == 'table') {
                                        //  var rows = [];
                                        console.log("table", template);
                                        var show = false;
                                        // if(!template.values.tid){
                                        //     template.values.tid = $scope.pid;
                                        //     template.values.invoice_items = 'invoice_items';
                                        // }
                                        async.map(template.values, function(val, callback) {
                                            console.log("val===========",val);
                                            if (val.length >0) {
                                                show = true;
                                            }
                                            callback(null, null);
                                        }, function(r, e) {
                                            if (show) {
                                                tabledata(template, v, function(rows) {
                                                    docDefinition.content.push({
                                                        table: {
                                                            // headers are automatically repeated if the table spans over multiple pages
                                                            // you can declare how many rows should be treated as headers
                                                            headerRows: 1,
                                                            body: rows,
                                                        },
                                                        absolutePosition: {
                                                            x: helper.px2pt(template.x),
                                                            y: helper.px2pt(template.y)
                                                        },
                                                        fontSize: template.font
                                                    });
                                                });
                                            }
                                        });

                                    }
                                });
                            });

                            function imgaedata(imgs, cb) {
                                console.log("imgsimgsimgsimgs",imgs);
                                getBase64Image(imgs, function(imagedata) {
                                    if (imagedata) {
                                        docDefinition.content.push({
                                            image: imagedata,
                                            absolutePosition: {
                                                x: helper.px2pt(imgs.x),
                                                y: helper.px2pt(imgs.y)
                                            }
                                        });
                                    }
                                    cb();
                                });
                            }

                            async.map(imgsarray, function(img, cb) {
                                imgaedata(img, function() {
                                    cb(null);
                                });
                            }, function(r) {
                                console.log("docDefinitiondocDefinition==",docDefinition);
                                if ($scope.pdfchecked == 'save') {
                                    pdfMake.createPdf(docDefinition).download($scope.printType + $scope.pid + '.pdf');
                                } else if ($scope.pdfchecked == 'print') {
                                    pdfMake.createPdf(docDefinition).print();
                                } else {
                                    pdfMake.createPdf(docDefinition).open();
                                }

                            });
                        })

                    }

                    $scope.tablemap = function(data, callback) {
                        async.map(data.ids, function(id) {
                            _.map(data.values[id.split('-')[1]], function(td) {
                                return callback(td);
                            });
                        });

                    }

                    function tabledataChild(template, callba) {
                        var rows = [];
                        console.log("temop", template);
                        // rows.push('222')
                       
                        var id = template.id.split('-');
                        var length = id.length - 1;
                        if (id[0] != "outstock") {
                            console.log("template.values",template.values);
                            console.log("id",id);
                            console.log("template",template);
                            if (_.isArray(template.values[id[length]])) {
                                async.map(template.values[id[length]], function(value, callback) {
                                    rows.push([{
                                        text: value + "",
                                        bold: true
                                    }]);
                                    callback(null, null);
                                }, function(error, result) {
                                    return callba(rows);

                                });
                            } else {
                                rows.push([template.values[id[length]] + ""]);
                                return callba(rows);
                            }
                        } else {

                            if (id[length] == "profit") {
                                var number = 0;
                                number = template.values.payment - template.values.post_cost;
                                intotalMoney(template, function(text) {
                                    number -= text;
                                    rows.push([{
                                        text: number + "",
                                        bold: true
                                    }])
                                    callba(rows);
                                })
                            } else if (id[length] == "Cost") {
                                intotalMoney(template, function(text) {
                                    rows.push([{
                                        text: text + "",
                                        bold: true
                                    }])
                                    callba(rows);
                                })
                            }
                        }
                    }

                    function intotalMoney(template, callbacks) {
                        var text = 0;
                        console.log(template)
                        async.map(template.values.outstock, function(cc, callback) {
                            _.map(cc, function(v) {
                                text += v.input_price * v.num;
                            });
                            callback(null, null);

                        }, function(err, re) {
                            text = text.toFixed(2);

                            return callbacks(text);
                        })
                    }

                    function translate(x) {
                        if (_.isArray(x)) {
                            _.map(x, function(a, k) {
                                x[k] = $filter("translate")(a);
                            });
                            return x;
                        } else if (_.isString(x)) {
                            return $filter("translate")(x);
                        } else {
                            return x;
                        }
                    }

                    function tabledata(template, v, callback) {
                        console.log(template);
                        var rows = [];

                        rows.push(translate(['title','item_id', 'skus_id', 'price', 'num', 'total_payment', 'remark']));
                        _.map(template.values.orders, function(td) {
                                console.log("td", td);
                                var row = [td.title + "",td.item_id + "", td.sku_outer_id + "", td.price + "", td.quantity + "", (td.quantity * td.price) + "", td.title];
                                rows.push(row);
                        });

                        return callback(rows);

                        switch ($scope.printType) {
                            case 'invoice':
                                rows.push(translate(['Description', 'Orderid', 'num', 'price', 'Subtotal', 'remark']));
                                $scope.tablemap(template, function(td) {
                                    var row = [td.name, template.values[template.ids[1].split('-')[1]] + "", td.quantity + "", td.price + "", (td.price * td.quantity) + "", (td.remark ? td.remark : "") + ""];
                                    rows.push(row);
                                });
                                break;
                            case 'shipping':
                                rows.push(translate(['title', 'item_id', 'skus_id', 'skus_name', 'Outgoing  quantity', 'itme_price', 'remark']));
                                var imgrray = [];
                                $scope.tablemap(template, function(td) {
                                    var row = [ //td.item_data.outer_id td.sku_data.outer_id td.sku_properties
                                        td.item_data.title + "", td.item_data.outer_id + "", td.sku_data.outer_id + "", td.sku_data.properties_name + "", td.quantity + "", td.price + "", td.remark != undefined ? td.remark : '' + ""
                                    ];
                                    rows.push(row);
                                });

                                break;
                            case 'picking':
                                rows.push(translate(['title', 'item_id', 'skus_id', 'skus_name', 'num', 'price', 'remark', 'Valid']));
                                var imgrray = [];

                                var trade = template.values.trade;
                                async.map(template.values.picking_wms_item, function(value) {
                                    async.map(template.values.wms_item, function(td) {
                                        if (value.stockout_detail == td.stock_out_item_id && trade.picking_id == v.picking_list_id) {
                                            var row = [
                                                value.stock_data.item_data.title + "", td.item_data.outer_id + "", td.item_data.sku.outer_id + "", td.item_data.sku.properties_name + "", value.quantity + "", td.price + "", td.remark + "", value.stock_data.expire_time + "" //, trade.tid + "", '', trade.receiver_address
                                            ];
                                            rows.push(row);
                                        }
                                    });
                                });
                                break;
                            case 'finance':
                                var id = template.id.split("-");
                                rows.push(translate(['item_id', 'title', 'skus_id', 'skus_name', 'itme_price', 'num', 'total_payment', 'remark']));

                                if (id[0] == "trade") {

                                    var imgrray = [];
                                    $scope.tablemap(template, function(td) {
                                        console.log("td", td);
                                        var row = [ //td.item_data.outer_id td.sku_data.outer_id td.sku_properties
                                            td.item_data.outer_id + "", td.title + "", td.sku_data.outer_id + "", td.sku_properties + "", td.price + "", td.num + "", td.total_payment + "", td.remark != undefined ? td.remark : '' + ""
                                        ];
                                        rows.push(row);
                                    });
                                } else {
                                    console.log("111");
                                    $scope.tablemap(template, function(tbody) {
                                        console.log(tbody);
                                        _.map(tbody, function(td) {
                                            var row = [ //td.item_data.outer_id td.sku_data.outer_id td.sku_properties
                                                td.item_data.outer_id + "", td.item_data.title + "", td.sku_data.outer_id + "", td.sku_data.properties_name + "", td.input_price + "", td.num + "", td.input_price * td.num + "", td.remark != undefined ? td.remark : '' + ""
                                            ];
                                            rows.push(row);
                                        })

                                    });
                                }

                                break;
                            case 'trade':
                                rows.push(translate(['title','item_id', 'skus_id', 'price', 'num', 'total_payment', 'remark']));
                                async.map(template.values.orders, function(td) {
                                    console.log("td", td);
                                    var row = [td.title + "",td.item_id + "", td.sku_outer_id + "", td.price + "", td.quantity + "", (td.quantity * td.price) + "", td.remark];
                                    rows.push(row);
                                });
                                break;
                            case 'returnform': // 'discount fee','payment',  td.discount_fee + "",td.payment+"",
                                rows.push(translate(['item_id', 'skus_id', 'num', 'price', 'remark']));
                                $scope.tablemap(template, function(td) {
                                    console.log("td", td);
                                    var row = [td.item_id + "", td.sku_id + "", td.num + "", td.price + "", td.remark];
                                    rows.push(row);
                                });
                                break;
                        }
                        return callback(rows);
                    }

                    $scope.getTrade = function(tid) {
                        var date = {};
                        var deferred = $q.defer();
                        dataService.orderOne(tid).then(function(v) {
                            deferred.resolve(v);
                            //return callback(v);
                        });
                        return deferred.promise;
                    }

                    var alertWin;

                    function showPop() {
                        alertWin = $.alert({
                            backdrop: 'static',
                            keyboard: true,
                            title: '<form class="sui-form" style="margin:0px;"><span>{{"Print"|translate}}{{title|translate}}</span></form>',
                            body: $templateCache.get("views/directives.printpdf.html"),
                            okBtn: '{{"ok"|translate}}',
                            closeBtn: true,
                            transition: true,
                            hasfoot: false,
                            height: '100px',
                            width: '300px',
                            show: function(e) {
                                $compile($(e.currentTarget).contents())($scope);
                                return true;
                            },
                            okHide: function(e) {
                                $timeout(function() {
                                    if ($scope.mult == 'true') {
                                        $scope.dhfNgModel = $scope.checkedAttach;
                                    } else {
                                        if ($scope.checkedAttach && $scope.xtype == 'url') {
                                            $scope.dhfNgModel = $scope.checkedAttach.path;
                                        } else {
                                            $scope.dhfNgModel = $scope.checkedAttach;
                                        }
                                    }
                                    if ($scope.setback) {
                                        $scope.setback({
                                            attach: $scope.dhfNgModel
                                        });
                                    }
                                });
                            },
                        });
                    }

                    $scope.hidePopWin = function() {
                        alertWin && alertWin.modal("hide");
                    }

                    $scope.goCreateTpl = function() {
                        window.open("#/print/list?type=" + $scope.printType, "_self");
                    }

                    $scope.print = function() {
                        window.print();
                    }

                    function getBase64Image(template, callback) {
                        var canvas = document.createElement("canvas");
                        var img = document.createElement("img");
                        img.src = template.value;

                        img.onload = function() {
                            var width, height;
                            if (template.width != undefined && template.width != 0) {
                                if (template.width.toString().match('px')) {
                                    width = template.width.toString().replace('px', "");
                                } else {
                                    width = template.width;
                                }

                            } else {
                                width = img.width;

                            }
                            if (template.height != undefined && template.height != 0) {
                                if (template.height.toString().match('px')) {
                                    height = template.height.toString().replace('px', "");
                                } else {
                                    height = template.height;
                                }

                            } else {
                                height = img.height;
                            }
                            width = helper.px2pt(width);
                            height = helper.px2pt(height);

                            // img.width = width;
                            // img.height = height;
                            canvas.width = width;
                            canvas.height = height
                            // Copy the image contents to the canvas
                            var ctx = canvas.getContext("2d");
                            ctx.drawImage(img, 0, 0, width, height);

                            // Get the data-URL formatted image
                            // Firefox supports PNG and JPEG. You could check img.src to
                            // guess the original format, but be aware the using "image/jpg"
                            // will re-encode the image.
                            var dataURL = canvas.toDataURL();
                            return callback(dataURL);
                        }
                    }

                    $scope.printTemplateList = function(type) {
                        $scope.printTplId = null;
                        return dataService.shopconfigGet({
                            page_no: 1,
                            page_size: 100,
                            query: {
                                'types': type
                            }
                        }, 0).then(function(result) {
                            if (result) {
                                $scope.shopconfigs = result.shopconfigs;
                                $scope.configLength = $scope.shopconfigs.length;
                                if (result.shopconfigs.length == 0) {
                                    return false;
                                }
                                //默认选中
                                var aa = JSON.parse(result.shopconfigs[0].value) ;
                                $scope.printTplId = result.shopconfigs[0];
                            }
                        });
                    }

                    $scope.expressList = function(express_id) {
                        return dataService.expressOne(express_id).then(function(list) {
                            if (list) {
                                $scope.express = list;
                            }
                        });
                    }

                    $scope.getPdfdata = function() {
                        var table = {
                            "express": "orderOne",
                            "invoice": "invoiceOneByInvoiceId",
                            "picking": "pickingOne",
                            "shipping": "getshipping",
                            "finance": "orderOne",
                            "payment": "paymentOne",
                            "trade": "orderOne",
                            "returnform": "returnformOne",
                        };
                        var pids = "" + $scope.pid;
                        var pidArray = pids ? pids.split(',') : [];
                        var PrimaryTable = [];
                        var index = 0;
                        async.map(pidArray, function(pid) {
                            index++;
                            if ($scope.printType != 'shipping') {
                                dataService[table[$scope.printType]](pid).then(function(result) {
                                    console.log("result",result);
                                    if ($scope.printType != "picking" && $scope.printType != "shipping") {
                                        PrimaryTable.push(result);
                                    } else if ($scope.printType == 'picking') {
                                        result.stockout['picking_wms_item'] = result.wms_item;
                                        PrimaryTable.push(result.stockout);
                                        // PrimaryTable.push({picking_wms_item: result.wms_item});
                                    }

                                    if (pidArray.length == PrimaryTable.length) {
                                        $scope.pdfsdata(PrimaryTable);
                                    }
                                });
                            } else if ($scope.printType == 'shipping') {
                                $scope[table[$scope.printType]](pid).then(function(x) {
                                    PrimaryTable.push(x);
                                    if (pidArray.length == PrimaryTable.length) {
                                        $scope.pdfsdata(PrimaryTable);
                                    }
                                });
                            }
                        });
                    }

                    $scope.pdfsdata = function(datas) {
                        var printobject = $scope.printTplId,
                            printconfig = JSON.parse(printobject.value);
                        var queryAction = [];
                        //查询字表类型名
                        var table = {
                            "orders": "orderOne",
                            "invoice": "invoiceOneByTid",
                            "express": "orderOne",
                            "shipping": "shippingOneByTid",
                            "outstock": "outData"
                        };
                        console.log("printconfigprintconfigprintconfigprintconfig",printconfig);
                        //循环配置模板
                        _.map(printconfig.item, function(item) {
                            console.log("queryAction",queryAction,$scope.printType);
                            //对配置模板的id进行分割第一项为隐射子表若有隐射的子表加入查询数组中
                            var ids = item.id.split('-');
                               console.log("ids",ids);
                            if (ids.length > 1 ) {
                                if (queryAction.length == 0 && ids[0] != $scope.printType ) {
                                    queryAction.push(ids[0]);
                                } else {
                                    var boolean = false;
                                    _.map(queryAction, function(querTable) {
                                        if (querTable == ids[0]) {
                                            boolean = true;
                                        } else if (querTable != ids[0] && ids[0] != $scope.printType && !boolean) {
                                            queryAction.push(ids[0]);
                                        }
                                    });
                                }
                            }
                        });
                        console.log("queryActionqueryActionqueryAction",queryAction,datas);
                        async.map(queryAction, function(tables, callback) {
                            console.log("table[tables]table[tables]",table[tables]);
                            _.map(datas, function(data) {
                                if (table[tables] == "outData") {
                                     $scope[table[tables]](data.tid, function(result) {
                                        data[tables] = result;
                                        callback(null, null);
                                    })
                                    console.log(data.tid, table[tables]);
                                }else if(table[tables] == "orderOne") {
                                    data[tables] = data.items ;
                                    callback(null, null);
                                }else{
                                     dataService[table[tables]](data.tid).then(function(result) {
                                        console.log(result, table[tables]);
                                        data[tables] = result;
                                        callback(null, null);
                                    });
                                }
                            });
                        }, function(err, results) {
                            var obj = {};
                            var array = [];
                            var ConfigItme = {};
                            
                            console.log("datasdatas",datas);
                            _.map(datas, function(data, k) {
                                var printconfigs = JSON.parse(printobject.value);
                                console.log("datasdatas",datas);
                                _.map(printconfigs.item, function(item) {
                                    var id = item.id.split('-');
                                    _.map(data, function(v, k) {
                                        if (item.type != 'table') {
                                            if (id.length <= 2) {
                                                if (k == id[1]) {
                                                    item.value = v;
                                                }
                                            } else if (id.length > 2) {

                                                if (k == id[1]) {
                                                    if (_.isArray(v)) {
                                                        _.map(v, function(object) {
                                                            var obj = object;
                                                            var ids = item.ids;

                                                            _.map(ids, function(chiId, length) {
                                                                if (length == ids.length - 1) {
                                                                    if (_.isArray(item.values[chiId])) {
                                                                        item.values[chiId].push(obj[chiId]);
                                                                    } else {
                                                                        item.values[chiId] = obj[chiId];
                                                                    }
                                                                } else {
                                                                    obj = obj[chiId];
                                                                }
                                                            });
                                                        });
                                                    } else {
                                                        var obj = v;
                                                        var ids = item.ids;
                                                        _.map(ids, function(chiId, length) {
                                                            if (length == ids.length - 1) {
                                                                if (_.isArray(item.values[chiId])) {
                                                                    if (_.isArray(obj)) {
                                                                        _.map(obj, function(chiObj) {
                                                                            item.values[chiId].push(chiObj[chiId]);
                                                                        });
                                                                    } else {
                                                                        item.values[chiId].push(obj[chiId]);
                                                                    }
                                                                } else {
                                                                    if (id[0] == "outstock") {
                                                                        item.values[chiId] = data[chiId];
                                                                    } else {
                                                                        item.values[chiId] = obj[chiId];
                                                                    }
                                                                }
                                                            } else {
                                                                if (item.idstype && item.idstype == "set") {
                                                                    item.values[chiId] = data[chiId];
                                                                } else if (!item.idstype || item.idstype == 'cycling') {
                                                                    obj = obj[chiId];
                                                                }
                                                            }
                                                        });
                                                    }

                                                }
                                            }
                                        } else {
                                            if(k == 'orders' && v.length >0){
                                                item.values[k] = v;
                                            }else{
                                                 _.map(item.ids, function(kk) {
                                                // console.log("kk",kk,k);
                                                    if (k == kk.split('-')[1]) {
                                                     item.values[k] = v;
                                                    }
                                                });
                                            }
                                        }
                                    });
                                });
                                array.push(printconfigs)
                            });
                            if ($scope.printType == 'shipping') {
                                $scope.shipping = datas;
                            }
                            $scope.printPdf = array;
                            console.log("$scope.printPdf",$scope.printPdf);
                            $scope.createPdfs();
                        });
                    }
                    $scope.shipping = function(shipping_id) {
                        return dataService.shippingOne(null, shipping_id).then(function(result) {
                            return result;
                        });
                    }

                    $scope.outData = function(tid, callbacks) {
                        var x = {};
                        //出库单
                        return dataService.stockoutGet({
                            query: {
                                "tid": tid
                            }
                        }).then(function(d) {
                            async.map(d.stocks, function(d1) {
                                x[d1.stockout_id] = [];
                                //拣货单
                                dataService.pickinglistOne(null, d1.stockout_id).then(function(p1) {
                                    //库存记录
                                    async.map(p1.wms_item, function(w, callback) {
                                        //库存
                                        dataService.stockOne(w.stock_id).then(function(stock) {
                                            //入库单，查询入库价格
                                            x[d1.stockout_id].push({
                                                stockout_id: d1.stockout_id,
                                                stock_id: w.stock_id,
                                                item_id: stock.item_id,
                                                sku_id: stock.sku_id,
                                                item_data: stock.item_data,
                                                sku_data: stock.sku_data,
                                                input_price: stock.input_price,
                                                num: w.quantity,
                                            });
                                            //console.log("-----", x);
                                            callback(null, null);
                                        });
                                    }, function(err, result) {
                                        callbacks(x)
                                    });
                                });
                            });
                        });
                    }


                    $scope.orderOne = function(tid, callbacks) {
                        var x = {};
                        // 订单数据
                        return dataService.orderOne({query: {"tid": tid}}).then(function(d) {
                            console.log("dddddddd",d);
                            callbacks(x);
                            // async.map(d.stocks, function(d1) {
                            //     x[d1.stockout_id] = [];
                            //     //拣货单
                            //     dataService.pickinglistOne(null, d1.stockout_id).then(function(p1) {
                            //         //库存记录
                            //         async.map(p1.wms_item, function(w, callback) {
                            //             //库存
                            //             dataService.stockOne(w.stock_id).then(function(stock) {
                            //                 //入库单，查询入库价格
                            //                 x[d1.stockout_id].push({
                            //                     stockout_id: d1.stockout_id,
                            //                     stock_id: w.stock_id,
                            //                     item_id: stock.item_id,
                            //                     sku_id: stock.sku_id,
                            //                     item_data: stock.item_data,
                            //                     sku_data: stock.sku_data,
                            //                     input_price: stock.input_price,
                            //                     num: w.quantity,
                            //                 });
                            //                 //console.log("-----", x);
                            //                 callback(null, null);
                            //             });
                            //         }, function(err, result) {
                            //             callbacks(x)
                            //         });
                            //     });
                            // });
                        });
                    }

                    //获取发货单数据
                    $scope.getshipping = function(shipping_id) {
                        return dataService.outOne(shipping_id).then(function(r) {
                            return dataService.orderOne(r.tid).then(function(trade) {
                                var shipping = {
                                    tid: r.tid,
                                    stockout_id: r.stockout_id,
                                    remark: "",
                                    total_fee: 0,
                                    discount_fee: 0,
                                    payment: 0,
                                    buyer_nick: trade.buyer_nick,
                                    shipping_items: [],
                                };

                                var orders = {};
                                _.map(trade.orders, function(b) {
                                    orders[b.item_id + "_" + b.sku_id] = b;
                                });

                                _.map(r.wms_item, function(a) {
                                    if (orders[a.item_id + "_" + a.sku_id]) {
                                        var xitem = orders[a.item_id + "_" + a.sku_id];
                                        var shippingItem = {
                                            item_id: a.item_id,
                                            title: xitem.title,
                                            sku_id: a.sku_id,
                                            sku_properties: xitem.sku_properties,
                                            price: xitem.price,
                                            quantity: a.quantity,
                                            total_fee: a.quantity * xitem.price,
                                            payment: xitem.total_payment,
                                            discount_fee: a.quantity * xitem.price - xitem.payment,
                                            item_data: a.item_data,
                                            sku_data: a.sku_data,
                                        };

                                        shipping.shipping_items.push(shippingItem);
                                        shipping.total_fee += shippingItem.total_fee;
                                        shipping.discount_fee += shippingItem.discount_fee;
                                        shipping.payment += shippingItem.payment;

                                    } else {
                                        helper.myAlert("error: trade data error", "#/shipping/list");
                                    }
                                });
                                return shipping;
                            });
                        });
                    }
                }
            ],
            link: function(scope, element) {

            }
        }
    });
})();